package com.gwtgeo.ui.client.mvp.adapter;

import java.util.ArrayList;
import java.util.List;

import com.gwtgeo.ui.client.mvp.HasValues;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class HasValuesListGridAdapter<T> implements HasValues<T> {

	private ListGrid grid;

	private RecordMapper<T> mapper;

	public HasValuesListGridAdapter(ListGrid grid, RecordMapper<T> mapper) {
		super();
		this.grid = grid;
		this.mapper = mapper;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> getValues() {
		List<T> values = new ArrayList<T>();
		ListGridRecord[] records = grid.getRecords();
		for (int i = 0; i < records.length; i++) {
			values.add(((ListGridRecordValue<T>) records[i]).getValue());
		}
		return values;
	}

	@Override
	public void setValues(List<T> values) {
		ListGridRecord[] records = new ListGridRecord[values.size()];
		for (int i = 0; i < records.length; i++) {
			records[i] = new ListGridRecordValue<T>(values.get(i), this.mapper);
		}
		grid.setData(records);
	}

	@Override
	public void addValue(T value) {
		this.grid.addData(new ListGridRecordValue<T>(value, this.mapper));
	}

	@Override
	public void addFirstValue(T value) {
		this.grid.getDataAsRecordList().addAt(
				new ListGridRecordValue<T>(value, this.mapper), 0);
	}

	@Override
	@SuppressWarnings("unchecked")
	public void selectValues(List<T> selection) {
		grid.deselectAllRecords();
		ListGridRecord[] records = grid.getRecords();
		for (int i = 0; i < records.length; i++) {
			ListGridRecordValue<T> record = (ListGridRecordValue<T>) records[i];
			if (selection.contains(record.getValue())) {
				grid.selectRecord(record);
			}
		}
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<T> getSelectedValues() {
		ListGridRecord[] records = grid.getSelection();
		List<T> selection = new ArrayList<T>();
		for (int i = 0; i < records.length; i++) {
			ListGridRecordValue<T> record = (ListGridRecordValue<T>) records[i];
			selection.add(record.getValue());
		}
		return selection;
	}

	@Override
	@SuppressWarnings("unchecked")
	public T getRowValue(int rowNumber) {
		return ((ListGridRecordValue<T>) this.grid.getRecord(rowNumber))
				.getValue();
	}

	@Override
	public void clear() {
		this.grid.setData(new ListGridRecord[0]);
	}
}
